import { HttpClient } from '@angular/common/http';
import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { res } from 'src/app/common/Interface';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.less'],
})
export class DetailComponent implements OnInit {
  @Input('commodity_id') commodity_id: number;
  constructor(
    private modal: NzModalService,
    private http: HttpClient,
    private msg: NzMessageService,
    private router: Router
  ) {}

  ngOnInit(): void {
    this.getDetail();
  }
  info = {
    commodity_name: '',
    price: 0,
    num: 0,
    unit: '',
    state: 1,
  };
  getDetail() {
    this.isVisible = false;
    this.http
      .get(`/commodity/detail/${this.commodity_id}`)
      .subscribe(({ code, msg, data }: res) => {
        if (code == 200) this.info = data;
      });
  }

  isVisible = false;
  handleOk() {
    this.http
      .post('/commodity/update', {
        ...this.changeObj,
        commodity_id: this.commodity_id,
      })
      .subscribe(({ code, msg, data }: res) => {
        code == 200 ? this.msg.success(msg) : this.msg.error(msg);
        if (code == 200) {
          this.getDetail();
        }
      });
  }
  handleCancel() {
    this.isVisible = false;
  }

  changeObj = {
    key: '',
    value: '',
    CN_key: '',
  };
  changeParams(evt, key, CN_key) {
    evt.preventDefault();
    this.isVisible = true;
    this.changeObj = {
      key,
      value: this.info[key],
      CN_key,
    };
  }
  changeSate(evt, state) {
    evt.preventDefault();
    this.modal.confirm({
      nzTitle: `<h1> 确认要${state ? '上' : '下'}架该商品吗</h1>`,
      nzOnOk: () => {
        this.changeObj = {
          key: 'state',
          value: state,
          CN_key: '状态',
        };
        this.http
          .post('/commodity/update', {
            ...this.changeObj,
            commodity_id: this.commodity_id,
          })
          .subscribe(({ code, msg, data }: res) => {
            code == 200
              ? this.msg.success(`${state ? '上' : '下'}架成功`)
              : this.msg.error(msg);
            if (code == 200) {
              this.getDetail();
            }
          });
      },
      nzCentered: true,
      nzCloseIcon: null,
    });
  }
  delCommodity() {
    this.modal.confirm({
      nzTitle: ' <h1> 确认要删除该商品吗</h1>',
      nzContent: '删除后将删除相关所有信息，包括售出和进货记录，且不可恢复！',
      nzOnOk: () => {
        this.http
          .get(`/commodity/del/${this.commodity_id}`)
          .subscribe(({ code, msg }: res) => {
            if (code == 200) {
              this.msg.success('删除成功');
              this.router.navigateByUrl('/main');
            }
          });
      },
      nzCentered: true,
      nzCloseIcon: null,
    });
  }
}
